package com.dlg.user.rpc.provider.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dlg.commons.constant.RedisKeyConstants;
import com.dlg.commons.util.Utils;
import com.dlg.user.dao.mysql.mappers.system.OjDictionaryMapper;
import com.dlg.user.dao.redis.CacheService;
import com.dlg.user.domain.system.OjDictionary;
import com.dlg.user.rpc.api.system.IDictionaryRpcService;
import com.dlg.commons.exception.DataFindException;
import com.dlg.user.rpc.api.vo.system.DictionaryRpcVo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 字典服务rpc层
 *
 * @author lhh@gongren.com
 * @since 2017年4月5日 下午4:47:41
 */
@com.alibaba.dubbo.config.annotation.Service
public class DictionaryRpcServiceImpl implements IDictionaryRpcService {

    @Autowired
    OjDictionaryMapper dictionaryMapper;

    @Autowired
    CacheService cacheService;

    @Override
    public List<OjDictionary> findByGroupCode(String groupCode, Short specialIdentification) {
        List<OjDictionary> result = new ArrayList<>();
        if (StringUtils.isBlank(groupCode)) {
            throw new DataFindException("groupCode is empty");
        }
        String key = RedisKeyConstants.getDictionaryByGroupAndStatus(groupCode, specialIdentification);
        if (cacheService.existsKey(key)){
            List<JSONObject> l = cacheService.getObject(key, List.class);
            for (JSONObject jsonObject:l){
                result.add(JSONObject.parseObject(jsonObject.toJSONString(),OjDictionary.class));
            }
            return result;
        }
        result = dictionaryMapper.findByGroupCode(groupCode, specialIdentification);
        cacheService.putObject(key, result);
        return result;
    }

    @Override
    public OjDictionary findByDataCode(String code) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(code)){
            return null;
        }
        String key = RedisKeyConstants.getDictionaryData(code);
        if (cacheService.existsKey(key)){
            return cacheService.getObject(key, OjDictionary.class);
        }
        OjDictionary ojDictionary = dictionaryMapper.findByDataCode(code);
        cacheService.putObject(key, ojDictionary);
        return ojDictionary;
    }


}
